﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using PeekWebApp.Common;
using PeekService;

namespace PeekWebApp.Management.AjaxHandler
{
    /// <summary>
    /// TourismInfoEditHandler 的摘要说明
    /// </summary>
    public class TourismInfoEditHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string action = context.Request["action"];
            if (action.Equals("Edit"))//编辑
            {
                string title = context.Request["title"].Trim();//标题
                string subtitle = context.Request["subtitle"].Trim();//标题
                string remark = context.Server.HtmlDecode(context.Request["remark"].Trim()); //摘要
                string desc = context.Server.HtmlDecode(context.Request["desc"]);//描述
                string recommand = context.Server.HtmlDecode(context.Request["recommand"]);//特别推荐
                string code = context.Request["hidCode"];
                string country = context.Request["hidcountryregion"];//国家地区
                string tourtype = context.Request["tourtype"];//景点类型
                string tags = context.Request["tags"];//关键字
                bool isSpecial =bool.Parse(context.Request["isSpecial"]);//是否推荐
                string coverName = context.Request["iscover"];//封面图片
                #region 地图信息
                string maptitle = context.Request["maptitle"];//地区标题
                string mapdesc =context.Server.HtmlDecode(context.Request["mapdesc"]);//地图描述信息
                string map = context.Server.HtmlDecode(context.Request["map"]);
                #endregion
                #region 票价信息
                //单程
                //string pricedan = context.Request["pricedan"];
                //string priceunitdan = context.Request["priceunitdan"];
                //string seatdan = context.Request["seatdan"];
                ////往返
                //string pricewangfan = context.Request["pricewangfan"];
                //string priceunitwangfan = context.Request["priceunitwangfan"];
                //string seatwangfan = context.Request["seatwangfan"];
                string ticketdan = context.Server.HtmlDecode(context.Request["ticketdan"]);
                string ticketwangfan= context.Server.HtmlDecode(context.Request["ticketwangfan"]);

                #endregion

                PeekService.TourismInfo model = new PeekService.TourismInfoService().GetModel(code);
                if (model == null)
                {
                    model = new PeekService.TourismInfo();
                    model.Code = Guid.NewGuid().ToString();
                    model.CreateID = "";
                    model.CreateTime = DateTime.Now;
                    model.State = 0;
                    model.Sort = new PeekService.ExtendService().GetSort("TourismInfo");
                    model.Desc = desc;
                    model.IsEspecially = isSpecial;
                    model.Title = title;
                    model.SubTitle = subtitle;
                    model.Remark = remark;
                    model.TicketDan = ticketdan;
                    model.TicketWangFan = ticketwangfan;
                    model.Tags = tags;
                    model.TypeCode = tourtype;
                    model.Hits = 0;
                    model.IsPublish = "否";
                    model.SpecialRecommand = recommand;
                    model.RegionCode = new CountriesRegionService().GetAll().Find(o => o.RegionPath == country).Code;
                    new PeekService.TourismInfoService().Add(model);
                }
                else
                {
                    model.Desc = desc;
                    model.IsEspecially = isSpecial;
                    model.Title = title;
                    model.SubTitle = subtitle;
                    model.Remark = remark;
                    model.TypeCode = tourtype;
                    model.Tags = tags;
                    model.TicketDan = ticketdan;
                    model.TicketWangFan = ticketwangfan;
                    model.SpecialRecommand = recommand;
                    model.RegionCode = new CountriesRegionService().GetAll().Find(o => o.RegionPath == country).Code;
                    new PeekService.TourismInfoService().Update(model);
                }
                #region 图片
                string filenamePath = context.Request["hidfilename"];//普通文件路径
                string thumbnailsnamePath = context.Request["hidthumbnailsname"];//缩略图路径
                string previewnamePath = context.Request["hidpreviewname"];//预览图路径
                string[] fileNamePathArray = filenamePath.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                string[] thumnailNamePathArray = thumbnailsnamePath.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                string[] previewNamePathArray = previewnamePath.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                PeekService.TourismInfo info = new PeekService.TourismInfoService().GetAll().Find(o => o.Title.Equals(title));
                new ExtendService().DeleteFileByTourismCode("SysFile",info.Code);
                bool hasCover = false;//防止出现多个封面
                for (int i = 0; i < fileNamePathArray.Length; i++)
                {
                   
                        ImageUpload imgFileName = new ImageUpload();
                        if (fileNamePathArray[i].IndexOf(":") > -1)//如果是新上传的肯定会含有冒号
                        {
                        imgFileName.SavePath = "~/images/normal/";
                        imgFileName.Upload(fileNamePathArray[i]);
                        
                        ImageUpload imgThumbnailName = new ImageUpload();
                        imgThumbnailName.SavePath = "~/images/thumbnails/";
                        imgThumbnailName.Upload(thumnailNamePathArray[i]);
                        ImageUpload imgPreview = new ImageUpload();
                        imgPreview.SavePath = "~/images/preview/";
                        imgPreview.Upload(previewNamePathArray[i]);
                        }
                        SysFile file = new SysFile();
                        file.Code = Guid.NewGuid().ToString();
                        file.TourismCode = info.Code;
                        file.CreateID = "";
                        file.CreateTime = DateTime.Now;
                        if (!hasCover)
                        {
                            if (!string.IsNullOrEmpty(coverName))
                            {
                                if (fileNamePathArray[i].Equals(coverName))
                                {
                                    file.IsCover = true;//是封面
                                    hasCover = true;//已有封面
                                }
                                else
                                {
                                    file.IsCover = false;//不是封面
                                }
                            }
                            else
                            {
                                if (i == 0)//默认第一个为封面图片
                                {
                                    file.IsCover = true;//是封面
                                    hasCover = true;//已有封面
                                }
                                else
                                {
                                    file.IsCover = false;
                                }
                            }
                        }
                        if (fileNamePathArray[i].IndexOf(":") > -1)//如果是新上传的肯定会含有冒号
                        {
                            file.FileName = file.RealName = fileNamePathArray[i].Substring(fileNamePathArray[i].LastIndexOf("\\") + 1);
                        }
                        else
                        {
                            file.FileName = file.RealName = fileNamePathArray[i].Substring(fileNamePathArray[i].LastIndexOf("/") + 1);
                        }
                        if (fileNamePathArray[i].IndexOf(":") > -1)//如果是新上传的肯定会含有冒号
                        {
                            file.ThumbnailsName = thumnailNamePathArray[i].Substring(thumnailNamePathArray[i].LastIndexOf("\\") + 1);
                        }
                        else
                        {
                            file.ThumbnailsName = thumnailNamePathArray[i].Substring(thumnailNamePathArray[i].LastIndexOf("/") + 1);
                        }
                        if (fileNamePathArray[i].IndexOf(":") > -1)//如果是新上传的肯定会含有冒号
                        {
                            file.PreviewName = previewNamePathArray[i].Substring(previewNamePathArray[i].LastIndexOf("\\") + 1);
                        }
                        else
                        {
                            file.PreviewName = previewNamePathArray[i].Substring(previewNamePathArray[i].LastIndexOf("/") + 1);
                        }
                        file.FilePath = "/images/normal/" + file.FileName;
                        file.ThumbnailsPath = "/images/thumbnails/" + file.ThumbnailsName;
                        file.PreviewPath = "/images/preview/" + file.PreviewName;
                        file.Remark = "";
                        file.State = 0;
                        file.Sort = new ExtendService().GetSort("SysFile");
                        new PeekService.SysFileService().Add(file);
                }
                #endregion
                #region 地图
                new ExtendService().DeleteFileByTourismCode("MapInfo", info.Code);
                MapInfo mapInfo = new MapInfo();//地图信息
                mapInfo.Title = maptitle;
                mapInfo.Remark = mapdesc;
                mapInfo.Content = map;
                mapInfo.Code = Guid.NewGuid().ToString();
                mapInfo.CreateID = "";
                mapInfo.CreateTime = DateTime.Now;
                mapInfo.Sort = new ExtendService().GetSort("MapInfo");
                mapInfo.TourismCode = info.Code;
                mapInfo.State = 0;
                new MapInfoService().Add(mapInfo);
                #endregion
                #region  票价


                //#region 单程票
                //new ExtendService().DeleteFileByTourismCode("TicketInfo", info.Code);
                //TicketInfo ticketInfoDan = new TicketInfo();
                //ticketInfoDan.Code = Guid.NewGuid().ToString();
                //ticketInfoDan.CreateID = "";
                //ticketInfoDan.CreateTime = DateTime.Now;
                //ticketInfoDan.Currency = "0";
                //ticketInfoDan.EffectiveDate = DateTime.Now;
                //ticketInfoDan.PriceUnit = priceunitdan;
                //ticketInfoDan.Remark = "";
                //ticketInfoDan.Seat = !string.IsNullOrEmpty(seatdan)?int.Parse(seatdan):0;
                //ticketInfoDan.Sort = new ExtendService().GetSort("TicketInfo");
                //ticketInfoDan.State = 0;
                //ticketInfoDan.TicketFare = !string.IsNullOrEmpty(pricedan)?decimal.Parse(pricedan):0;
                //ticketInfoDan.TicketType = 0;
                //ticketInfoDan.TourismCode = info.Code;
                //ticketInfoDan.SoldSeat = 0;
                //new PeekService.TicketInfoService().Add(ticketInfoDan);
                //#endregion
                //#region 往返票
                //TicketInfo ticketInfoWangFan = new TicketInfo();
                //ticketInfoWangFan.Code = Guid.NewGuid().ToString();
                //ticketInfoWangFan.CreateID = "";
                //ticketInfoWangFan.CreateTime = DateTime.Now;
                //ticketInfoWangFan.Currency = "0";
                //ticketInfoWangFan.EffectiveDate = DateTime.Now;
                //ticketInfoWangFan.PriceUnit = priceunitwangfan;
                //ticketInfoWangFan.Remark = "";
                //ticketInfoWangFan.Seat = !string.IsNullOrEmpty(seatwangfan) ? int.Parse(seatwangfan) : 0;
                //ticketInfoWangFan.Sort = new ExtendService().GetSort("TicketInfo");
                //ticketInfoWangFan.State = 0;
                //ticketInfoWangFan.TicketFare = !string.IsNullOrEmpty(pricewangfan) ? decimal.Parse(pricewangfan) : 0;
                //ticketInfoWangFan.TicketType = 0;
                //ticketInfoWangFan.TourismCode = info.Code;
                //ticketInfoWangFan.SoldSeat = 0;
                //new PeekService.TicketInfoService().Add(ticketInfoWangFan);
                //#endregion
                #endregion

                context.Response.Redirect("../TourismInfo/List.aspx");
            }
            else if (action.Equals("CheckTitle"))
            {
                string title = context.Request["title"];
                string code = context.Request["id"];
                if (code != "-1" && !string.IsNullOrEmpty(code))
                {
                    context.Response.Write("true");
                }
                else
                {
                    string isExsits = new ExtendService().CheckExistByOneColumn("TourismInfo", "Title", title);
                    context.Response.Write(isExsits);
                }
            }

            else //绑定
            {
                string code = context.Request["hidCode"];
                int result = 0;
                PeekService.TourInfoModel model = new PeekService.ExtendService().GetAllByTypeRegion(1, 1, out result, "", "", code,"","")[0];
                List<SysFile> fileList = new List<SysFile>();
                fileList = new ExtendService().GetFileByTourismCode(code);
                MapInfo mapInfo = new ExtendService().GetMapByTourismCode(code);
                //List<TicketInfo> ticketList = new ExtendService().GetTicketInfoByTourismCode(code);
                //context.Response.Write(PeekService.CommonService.ConvertToJSON(new { model, file = fileList,map=mapInfo,ticket=ticketList }));
              
                context.Response.Write(PeekService.CommonService.ConvertToJSON(new { model, file = fileList, map = mapInfo }));

            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}